from typing import List
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select

from app.core.database import get_async_session
from app.schemas.minutes import (
    Minutes, MinutesCreate, MinutesUpdate,
    MinutesGenerationRequest, MinutesExportRequest
)
from app.models.minutes import Minutes as MinutesModel, MinutesStatus
from app.models.meeting import Meeting as MeetingModel
from app.models.user import User as UserModel

router = APIRouter()


@router.post("/", response_model=Minutes)
async def create_minutes(
    minutes: MinutesCreate,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """创建会议纪要"""
    # 检查会议是否存在且属于当前用户
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    meeting_query = select(MeetingModel).where(
        MeetingModel.id == minutes.meeting_id,
        MeetingModel.user_id == user_id
    )
    meeting_result = await db.execute(meeting_query)
    meeting = meeting_result.scalar_one_or_none()

    if not meeting:
        raise HTTPException(status_code=404, detail="会议不存在")

    # 检查是否已有纪要
    existing_minutes_query = select(MinutesModel).where(
        MinutesModel.meeting_id == minutes.meeting_id
    )
    existing_result = await db.execute(existing_minutes_query)
    if existing_result.scalar_one_or_none():
        raise HTTPException(status_code=400, detail="该会议已有纪要")

    # 创建纪要
    db_minutes = MinutesModel(**minutes.dict())
    db.add(db_minutes)
    await db.commit()
    await db.refresh(db_minutes)
    return db_minutes


@router.get("/{minutes_id}", response_model=Minutes)
async def get_minutes(
    minutes_id: int,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """获取会议纪要详情"""
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    query = select(MinutesModel).join(MeetingModel).where(
        MinutesModel.id == minutes_id,
        MeetingModel.user_id == user_id
    )
    result = await db.execute(query)
    minutes = result.scalar_one_or_none()

    if not minutes:
        raise HTTPException(status_code=404, detail="会议纪要不存在")

    return minutes


@router.put("/{minutes_id}", response_model=Minutes)
async def update_minutes(
    minutes_id: int,
    minutes_update: MinutesUpdate,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """更新会议纪要"""
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    # 获取纪要
    query = select(MinutesModel).join(MeetingModel).where(
        MinutesModel.id == minutes_id,
        MeetingModel.user_id == user_id
    )
    result = await db.execute(query)
    minutes = result.scalar_one_or_none()

    if not minutes:
        raise HTTPException(status_code=404, detail="会议纪要不存在")

    # 更新字段
    update_data = minutes_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(minutes, field, value)

    await db.commit()
    await db.refresh(minutes)
    return minutes


@router.delete("/{minutes_id}")
async def delete_minutes(
    minutes_id: int,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """删除会议纪要"""
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    # 获取纪要
    query = select(MinutesModel).join(MeetingModel).where(
        MinutesModel.id == minutes_id,
        MeetingModel.user_id == user_id
    )
    result = await db.execute(query)
    minutes = result.scalar_one_or_none()

    if not minutes:
        raise HTTPException(status_code=404, detail="会议纪要不存在")

    await db.delete(minutes)
    await db.commit()
    return {"message": "会议纪要已删除"}


@router.post("/generate", response_model=dict)
async def generate_minutes(
    request: MinutesGenerationRequest,
    background_tasks: BackgroundTasks,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """生成会议纪要（异步任务）"""
    user_id = current_user.id if current_user else 1  # 临时使用固定用户ID

    # 检查会议是否存在且属于当前用户
    meeting_query = select(MeetingModel).where(
        MeetingModel.id == request.meeting_id,
        MeetingModel.user_id == user_id
    )
    meeting_result = await db.execute(meeting_query)
    meeting = meeting_result.scalar_one_or_none()

    if not meeting:
        raise HTTPException(status_code=404, detail="会议不存在")

    # TODO: 添加后台任务来生成纪要
    # background_tasks.add_task(generate_minutes_task, request.meeting_id, request.template_name)

    return {
        "message": "会议纪要生成任务已启动",
        "meeting_id": request.meeting_id,
        "template": request.template_name
    }


@router.post("/export")
async def export_minutes(
    request: MinutesExportRequest,
    current_user: UserModel = None,  # TODO: 添加认证依赖
    db: AsyncSession = Depends(get_async_session)
):
    """导出会议纪要"""
    # TODO: 实现纪要导出功能
    return {
        "message": "导出功能开发中",
        "format": request.format,
        "template": request.template
    }